package org.mii.safeguard_v1.security.entity;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.mii.safeguard_v1.base.entity.IdEntity;

/**
 * 用户令牌,暂时主要和用户恢复密码操作相关。
 */
@Entity
@Table(name = "tokens")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Token extends IdEntity {

	private String key;

	private String type;

	private Date expireTime;

	private User user;

	public Token() {

	}

	public Token(String key, String type, Date expireTime, User user) {
		this.key = key;
		this.type = type;
		this.expireTime = expireTime;
		this.user = user;
	}

	@Column(name = "token_key", length = 64, nullable = false, unique = true)
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	@Column(name = "type", length = 16, nullable = false)
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "expiration_ts", nullable = false)
	public Date getExpireTime() {
		return expireTime;
	}

	public void setExpireTime(Date expireTime) {
		this.expireTime = expireTime;
	}

	@ManyToOne(targetEntity = User.class, cascade = { CascadeType.PERSIST,
			CascadeType.MERGE }, fetch = FetchType.LAZY)
	@JoinColumn(name = "user_id")
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof Token))
			return false;
		final Token token = (Token) obj;
		return getKey().equals(token.getKey());
	}

	public String toString() {
		return "Token ('" + getId() + "'), " + "key: '" + getKey() + "'"
				+ "type: '" + getType() + "'" + "expireTime: '"
				+ getExpireTime() + "'";
	}
}
